const API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
const QWEN_API_KEY = "sk-a0d29dafdcf74318b37f6394d2f9bb7c"; // 替换为你的密钥

/**
 * 识别油单/仪表盘信息（支持1~2张图，分别调用后合并）
 * @param {Array<string>} imagePaths - 图片本地路径数组（最多2张）
 * @returns {Promise<Object>} 合并后的 fuelRecord
 */
export async function recognizeFuelRecord(imagePaths = []) {
  if (!imagePaths.length) throw new Error("请至少提供一张图片");

  const prompt = `
你将获得一张图片，可能是车辆仪表盘或加油小票。
请提取以下字段，输出纯 JSON 对象（不要任何说明文字）：
{
  "date": "YYYY-MM-DD",
  "mileage": "公里数（仅仪表盘有）",
  "liters": "加油升数",
  "price_per_liter": "单价（元）",
  "oil_pump_amount": "油枪金额（元）",
  "actual_amount": "实付金额（元）"
}
- 若字段无法识别，填空字符串 ""
- 只输出 JSON，不要 markdown 或其他内容
`;

  // 分别调用每张图
  const results = [];
  for (const path of imagePaths) {
    try {
      // 获取带 data:image/...;base64, 前缀的完整 Base64
      const base64WithPrefix = await fileToBase64WithPrefix(path);
      const result = await callQwenVLForSingleImage(base64WithPrefix, prompt);
      results.push(result);
    } catch (err) {
      console.warn(`处理图片 ${path} 失败:`, err);
      results.push({}); // 空对象不影响合并
    }
  }

  // 合并：优先取非空值
  const merged = {
    date: "",
    mileage: "",
    liters: "",
    price_per_liter: "",
    oil_pump_amount: "",
    actual_amount: ""
  };

  for (const res of results) {
    for (const key in merged) {
      if (!merged[key] && res[key] !== undefined && res[key] !== "") {
        merged[key] = res[key];
      }
    }
  }

  return merged;
}

/**
 * 调用 Qwen-VL 模型（单图）
 */
function callQwenVLForSingleImage(base64Image, prompt) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: API_URL,
      method: "POST",
      header: {
        "Authorization": `Bearer ${QWEN_API_KEY}`,
        "Content-Type": "application/json"
      },
      data: {
        model: "qwen3-vl-plus",
        input: {
          messages: [{
            role: "user",
            content: [
              { image: base64Image },
              { text: prompt }
            ]
          }]
        }
      },
      success: (res) => {
        const { data } = res;
        if (data?.output?.choices?.[0]?.message?.content?.[0]?.text) {
          try {
            const jsonText = data.output.choices[0].message.content[0].text;
            const json = JSON.parse(jsonText);
            resolve(json);
          } catch (e) {
            console.error("AI 返回非 JSON:", jsonText);
            reject(new Error("AI 返回格式错误"));
          }
        } else {
          console.error("API 返回异常:", data);
          reject(new Error("API 返回无有效内容"));
        }
      },
      fail: (err) => {
        console.error("请求失败:", err);
        reject(new Error(`网络请求失败: ${err.errMsg}`));
      }
    });
  });
}

/**
 * 将本地图片转为带 MIME 前缀的 Base64（如 data:image/jpeg;base64,...）
 */
function fileToBase64WithPrefix(filePath) {
  return new Promise((resolve, reject) => {
    const path = filePath.replace(/^file:\/\//, '');
    plus.io.resolveLocalFileSystemURL(path, (entry) => {
      entry.file((file) => {
        const reader = new plus.io.FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = () => reject(new Error("读取文件失败"));
        reader.readAsDataURL(file);
      }, reject);
    }, reject);
  });
}